package com.ezjie.baselib.core.exception;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.lang.Thread.UncaughtExceptionHandler;


import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Looper;
import android.util.Log;

/**
 * 使用�?UncaughtException.getInstance().init(); UncaughtException.getInstance().setContext(this);
 * 
 * @author renyangyang
 * 
 */
public class UncaughtException implements UncaughtExceptionHandler {
	private static UncaughtException mUncaughtException;
	private Context context;

	public synchronized static UncaughtException getInstance() {
		if (mUncaughtException == null) {
			mUncaughtException = new UncaughtException();
		}
		return mUncaughtException;
	}

	/**
	 * 初始化，把当前对象设置成UncaughtExceptionHandler处理器
	 */
	public void init() {
		Thread.setDefaultUncaughtExceptionHandler(mUncaughtException);
	}

	public void setContext(Context context) {
		this.context = context;
	}

	@Override
	public void uncaughtException(Thread thread, Throwable ex) {
		// TODO Auto-generated method stub
		// 处理异常,我们还可以把异常信息写入文件，以供后来分析。
		showDialog(ex);
	}

	// 对话框提示 出现异常
	private void showDialog(final Throwable ex) {
		new Thread() {
			@Override
			public void run() {
				Looper.prepare();// 大爷我崩溃了...
				new AlertDialog.Builder(context).setTitle("崩溃信息，请告知任阳阳")
						.setCancelable(false)
						.setMessage(getStack(ex))
						.setNeutralButton("我知道了", new OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								System.exit(0);
							}
						}).create().show();
				Looper.loop();
			}

			private String getStack(Throwable e) {
				String error = null;
				if (e != null) {
					ByteArrayOutputStream baos = null;
					PrintStream ps = null;
					try {
						baos = new ByteArrayOutputStream();
						ps = new PrintStream(baos);
						e.printStackTrace(ps);
						error = baos.toString();
						baos.close();
						ps.close();
					} catch (Exception e1) {
						error = e.toString();
					} finally {
						baos = null;
						ps = null;
					}
				}
				return error;
			}
		}.start();
	}

}
